import type { MapMouseEvent } from 'mapbox-gl'
import { markRaw } from 'vue'
import { openContextMenuX, type ContextMenuEntry } from '@/widgets'
import { listSelect } from '@/common/list-select'
import { getMapItemTypeSpec, type MapItemTypeSpec } from '../base'
import { searchMapItems } from '../map-index'
import { selectMapItem } from './core'

function chooseAndSelect(opts: MapItemTypeSpec<any>, data: any[]) {
  listSelect<any>({
    title: `选择${opts.typeName}[${data.length}]`,
    icon: opts.icon,
    data: markRaw(data),
    getItemName: opts.getName,
    callback: (e) => {
      selectMapItem(opts.type, e)
    }
  })
}

function makeContextMenus(opts: MapItemTypeSpec<any>, data: any[], showIcon: boolean) {
  const menu: ContextMenuEntry[] = []
  let i = 0
  const icon = showIcon ? opts.icon : undefined
  for (const item of data) {
    if (i > 6) {
      menu.push({
        text: '显示更多...',
        // onClick: () => console.log('show more', opts.type)
        onClick: () => chooseAndSelect(opts, data)
      })
      break
    }
    menu.push({
      icon,
      text: opts.getName(item),
      onClick: () => selectMapItem(opts.type, item)
    })
    i++
  }
  return menu
}

export function selectMapItemOnMap(evt: MapMouseEvent) {
  const m = evt.target
  const zoom = m.getZoom()
  const scale = Math.pow(2, zoom)
  const r = 10 / scale
  const { lng, lat } = evt.lngLat
  const se = searchMapItems(lng, lat, r)
  if (!se) {
    return
  }
  const e = Object.values(se)
  if (e.length === 1) {
    const g = e[0]
    if (g.items.length === 0) {
      return
    }
    if (g.items.length === 1) {
      selectMapItem(g.type, g.items[0])
      return
    }
    const spec = getMapItemTypeSpec(g.type)
    if (!spec) {
      return
    }
    const menu = makeContextMenus(spec, g.items, false)
    menu.splice(0, 0, {
      icon: spec.icon,
      text: `${spec.typeName}(${g.items.length})`
    })
    openContextMenuX(menu, evt.originalEvent)
    return
  }

  const menu: ContextMenuEntry[] = []
  const menu1: ContextMenuEntry[] = []
  for (const g of e) {
    if (!g.items || g.items.length === 0) {
      continue
    }
    const spec = getMapItemTypeSpec(g.type)
    if (!spec) {
      continue
    }
    if (g.items.length <= 3) {
      const subMenu = makeContextMenus(spec, g.items, false)
      menu.push({
        icon: spec.icon,
        text: `${spec.typeName}(${g.items.length})`
      })
      menu.push(...subMenu)
    } else {
      const subMenu = makeContextMenus(spec, g.items, false)
      // if (menu.length > 0) {
      //   menu.push('-')
      // }
      menu1.push({
        icon: spec.icon,
        text: `${spec.typeName}(${g.items.length})`,
        children: subMenu
      })
    }
  }
  if (menu1.length > 0) {
    menu.push(...menu1)
  }

  openContextMenuX(menu, evt.originalEvent)
}
